<template>
  <div>
    <!-- 搜索栏 -->
    <form action="/">
      <van-search
        v-model="searchText"
        placeholder="请输入搜索关键词"
        show-action
        @cancel="$router.back()"
        @search="onSearch"
        @focus="isResultShow = false"
      />
    </form>

    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :searchText="searchText"></search-result>
    <!-- 搜索建议 -->
    <search-suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    ></search-suggestion>
    <!-- 搜索记录 -->
    <search-history
      v-else
      :searchHistory="searchHistory"
      @handleAllRemover="handleAllRemover"
    ></search-history>
  </div>
</template>
<script>
import searchSuggestion from "./components/searchSuggestion";
import searchHistory from "./components/searchHistory";
import searchResult from "./components/searchResult";
import { getSearchHistories } from "@/request/home";
import { mapState } from "vuex";

export default {
  data() {
    return {
      searchText: "",
      isResultShow: false,
      searchHistory: []
    };
  },
  components: {
    searchSuggestion,
    searchHistory,
    searchResult
  },
  computed: {
    ...mapState(["user"])
  },
  async created() {
    if (this.user) {
      // 拿线上的记录
      const { data } = await getSearchHistories();
      this.searchHistory = data.data.keywords;
    } else {
      // 拿本地的记录
      const temp =
        JSON.parse(window.localStorage.getItem("searchHistory")) || [];
      this.searchHistory = temp;
    }
  },

  methods: {
    // 监听输入
    onSearch(val) {
      this.searchText = val;
      const index = this.searchHistory.indexOf(val);
      if (index !== -1) {
        this.searchHistory.splice(index, 1);
      }
      this.searchHistory.unshift(this.searchText);
      // 保存在本地
      window.localStorage.setItem(
        "searchHistory",
        JSON.stringify(this.searchHistory)
      );
      this.isResultShow = true;
    },
    // 刷新用户的搜索记录
    async handleAllRemover() {
      const { data } = await getSearchHistories();
      this.searchHistory = data.data.keywords;
    }
  }
};
</script>

<style>
</style>